package com.querie.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;

public class SQLKeyword {

	public static final String sqlKey[] = { "TOP","ADD", "ALL", "ALTER", "ANALYZE",
			"AND", "AS", "ASC", "ASENSITIVE", "BEFORE", "BETWEEN", "BIGINT",
			"BINARY", "BLOB", "BOTH", "BY", "CALL", "CASCADE", "CASE",
			"CHANGE", "CHAR", "CHARACTER", "CHECK", "COLLATE", "COLUMN",
			"CONDITION", "CONSTRAINT", "CONTINUE", "CONVERT", "CREATE",
			"CROSS", "CURRENT_DATE", "CURRENT_TIME", "CURRENT_TIMESTAMP",
			"CURRENT_USER", "CURSOR", "DATABASE", "DATABASES", "DAY_HOUR",
			"DAY_MICROSECOND", "DAY_MINUTE", "DAY_SECOND", "DECIMAL",
			"DECLARE", "DEFAULT", "DELAYED", "DELETE", "DESC", "DESCRIBE",
			"DETERMINISTIC", "DISTINCT", "DISTINCTROW", "DIV", "DOUBLE",
			"DROP", "DUAL", "EACH", "ELSE", "ELSEIF", "ENCLOSED", "ESCAPED",
			"EXISTS", "EXIT", "EXPLAIN", "FALSE", "FETCH", "FLOAT", "FLOAT4",
			"FLOAT8", "FOR", "FORCE", "FOREIGN", "FROM", "FULLTEXT", "GRANT",
			"GROUP", "HAVING", "HIGH_PRIORITY", "HOUR_MICROSECOND",
			"HOUR_MINUTE", "HOUR_SECOND", "IF", "IGNORE", "IN", "INDEX",
			"INFILE", "INNER", "INOUT", "INSENSITIVE", "INSERT", "INT", "INT1",
			"INT2", "INT3", "INT4", "INT8", "INTEGER", "INTERVAL", "INTO",
			"IS", "ITERATE", "JOIN", "KEY", "KEYS", "KILL", "LEADING", "LEAVE",
			"LEFT", "LIKE", "LIMIT", "LINES", "LOAD", "LOCALTIME",
			"LOCALTIMESTAMP", "LOCK", "LONG", "LONGBLOB", "LONGTEXT", "LOOP",
			"LOW_PRIORITY", "MATCH", "MEDIUMBLOB", "MEDIUMINT", "MEDIUMTEXT",
			"MIDDLEINT", "MINUTE_MICROSECOND", "MINUTE_SECOND", "MOD",
			"MODIFIES", "NATURAL", "NOT", "NO_WRITE_TO_BINLOG", "NULL",
			"NUMERIC", "ON", "OPTIMIZE", "OPTION", "OPTIONALLY", "OR", "ORDER",
			"OUT", "OUTER", "OUTFILE", "PRECISION", "PRIMARY", "PROCEDURE",
			"PURGE", "READ", "READS", "REAL", "REFERENCES", "REGEXP",
			"RELEASE", "RENAME", "REPEAT", "REPLACE", "REQUIRE", "RESTRICT",
			"RETURN", "REVOKE", "RIGHT", "RLIKE", "SCHEMA", "SCHEMAS",
			"SECOND_MICROSECOND", "SELECT", "SENSITIVE", "SEPARATOR", "SET",
			"SHOW", "SMALLINT", "SONAME", "SPATIAL", "SPECIFIC", "SQL",
			"SQLEXCEPTION", "SQLSTATE", "SQLWARNING", "SQL_BIG_RESULT",
			"SQL_CALC_FOUND_ROWS", "SQL_SMALL_RESULT", "SSL", "STARTING",
			"STRAIGHT_JOIN", "TABLE", "TERMINATED", "THEN", "TINYBLOB",
			"TINYINT", "TINYTEXT", "TO", "TRAILING", "TRIGGER", "TRUE", "UNDO",
			"UNION", "UNIQUE", "UNLOCK", "UNSIGNED", "UPDATE", "USAGE", "USE",
			"USING", "UTC_DATE", "UTC_TIME", "UTC_TIMESTAMP", "VALUES",
			"VARBINARY", "VARCHAR", "VARCHARACTER", "VARYING", "WHEN", "WHERE",
			"WHILE", "WITH", "WRITE", "XOR", "YEAR_MONTH", "ZEROFILL",
			"ASENSITIVE", "CALL", "CONDITION", "CONNECTION", "CONTINUE",
			"CURSOR", "DECLARE", "DETERMINISTIC", "EACH", "ELSEIF", "EXIT",
			"FETCH", "GOTO", "INOUT", "INSENSITIVE", "ITERATE", "LABEL",
			"LEAVE", "LOOP", "MODIFIES", "OUT", "READS", "RELEASE", "REPEAT",
			"RETURN", "SCHEMA", "SCHEMAS", "SENSITIVE", "SPECIFIC", "SQL",
			"SQLEXCEPTION", "SQLSTATE", "SQLWARNING", "TRIGGER", "UNDO",
			"UPGRADE", "WHILE", ">", "<", "=" , ")", "'"};
	public static final ArrayList<String> sqlKeyList = new ArrayList<String>(
			Arrays.asList(sqlKey));

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println(isNumeric("1935"));
	}

	public static boolean isSQLKeyWord(String token) {
		boolean result = false;

		result = sqlKeyList.contains(token.toUpperCase());

		return result;
	}

	public static boolean containsSQLKeyWord(String token) {
		boolean result = false;

		for (String s : sqlKey) {
			if (token.toUpperCase().equalsIgnoreCase(s)) {
				result = true;
				break;
			}
		}
		return result;
	}

	public static boolean isNumeric(String token) {
		return token.matches("-?\\d+(\\.\\d+)?") || token.startsWith("0x");
	}

	public static boolean containsOperator(String token) {
		boolean result = false;

		if (	   token.contains("+") 
				|| token.contains("/") 					|| token.contains("\\")
				|| token.contains("*")  				|| token.contains("-")
				|| token.contains("%")  				|| token.toLowerCase().contains("and")
				|| token.toLowerCase().contains("or") 	|| token.contains("=")
				|| token.contains("!=") 				|| token.contains("<")
				|| token.contains(">")  				|| token.contains("<=")
				|| token.contains(">=") 				|| token.contains("|") || token.contains("&")
				|| token.contains("!")  				|| token.contains("^") 
				|| token.contains("(")  				|| token.contains(")") 
				|| token.contains("[")  				|| token.contains("]") 
				|| token.contains("'")  				|| token.contains("\"")
				|| token.contains(",")					|| token.contains("'"))
			result = true;

		return result;
	}

	public static String fetchFragmentFromFunction(String token) {
		String result = "";
		int indexOfOpenBracket = token.lastIndexOf("(");
		int indexOfLastBracket = token.indexOf(")");

		if (indexOfOpenBracket > 0) {
			
			if (indexOfLastBracket > 0)
				result = token.substring(indexOfOpenBracket + 1, indexOfLastBracket);
			else
				result = token.substring(indexOfOpenBracket + 1);

			if (isNumeric(result) && containsOperator(result)) {
				result = "";
			}
		} else if (indexOfLastBracket > 0 ) {
			result = token.substring(0, indexOfLastBracket - 1);
			if (isNumeric(result) && containsOperator(result)) {
				result = "";
			}
		}
		return result;
	}

	public static String insertSpacesForOperators(String token) {
		token = token.replace("+", " + ");
		token = token.replace("/"," / ");
		token = token.replace("\\", " \\ ");
		token = token.replace("*", " * ");
		token = token.replace("-"," - ");
		token = token.replace("!"," ! ");
		token = token.replace("%"," % ");
		token = token.toLowerCase().replace("and"," and ");
		token = token.toLowerCase().replace("or"," or ");
		token = token.replace("="," = ");
		token = token.replace("!="," != ");
		token = token.replace("<"," < ");
		token = token.replace(">"," > ");
		token = token.replace("<="," <= ");
		token = token.replace(">="," >= ");
		token = token.replace("^"," ^ ");
		token = token.replace("("," ( ");
		token = token.replace(")"," ) ");
		token = token.replace("["," [ ");
		token = token.replace("]"," ] ");
		token = token.replace("\""," \" ");
		token = token.replace(","," , ");
		token = token.replace("'"," ' ");
		return token;
	}
	
}
